package ru.ksu.ktk.diploma.sdi.mapping.thesauri;

import gate.util.GateException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import ru.edu.niimm.mapping.linguistic.NLP;
import ru.ksu.ktk.diploma.sdi.mapping.Triple;
import ru.ksu.ktk.diploma.sdi.util.DescriptorsUtil;

public class ThesauriService {
    protected static final Log log = LogFactory.getLog(ThesauriService.class);
    /**
     * NLP to parse thesauri descriptors
     */
    private NLP nlpService;
    /**
     * NLP key
     */
    private String nlpKey;
    /**
     * importing thesauri relative path (URI)
     */
    private String thesauriUri;
    /**
     * Thesauri language
     */
    private String thesauriLanguage;

    /**
     * complete triples with thesauri descriptors
     * 
     * @param triples
     * @throws IOException
     * @throws GateException
     */
    public List<Triple> completeWithDescriptors(List<Triple> triples) {
        List<Triple> completedTriples = new ArrayList<Triple>();
        for (Triple triple : triples){
            String rdfsLabel = triple.getRdfsLabel();
            List<String> descriptorsIdList;
            try{
                descriptorsIdList =
                    nlpService.execOnFieldIndex(nlpKey, thesauriUri, new String[] {rdfsLabel}, thesauriLanguage);
            }
            catch (GateException e){
                log.error(e);
                throw new IllegalStateException(String.format("couldn't parse thesauri descriptors of triple: %s",
                    triple.toString()));
            }
            catch (IOException e){
                log.error(e);
                throw new IllegalStateException(String.format("couldn't parse thesauri descriptors of triple: %s",
                    triple.toString()));
            }
            List<ThesauriDescriptor> thesauriDescriptors = DescriptorsUtil.getThesauriDescriptors(descriptorsIdList);
            triple.setDescriptors(thesauriDescriptors);

        }
        return completedTriples;
    }

    public String getThesauriLanguage() {
        return thesauriLanguage;
    }

    public void setThesauriLanguage(String thesauriLanguage) {
        this.thesauriLanguage = thesauriLanguage;
    }

    public NLP getNlpService() {
        return nlpService;
    }

    public void setNlpService(NLP nlpService) {
        this.nlpService = nlpService;
    }

    public String getNlpKey() {
        return nlpKey;
    }

    public void setNlpKey(String nlpKey) {
        this.nlpKey = nlpKey;
    }

    public String getThesauriUri() {
        return thesauriUri;
    }

    public void setThesauriUri(String thesauriUri) {
        this.thesauriUri = thesauriUri;
    }
}
